//
//  RegisterView.m
//  eticket
//
//  Created by AnhQuocNguyen on 4/15/13.
//  Copyright (c) 2013 SoinMedia. All rights reserved.
//

#import "RegisterView.h"

@implementation RegisterView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
- (void)dealloc {
    [_scrollParentView release];
    [_txtEmail release];
    [_txtPass release];
    [_txtConfirmPass release];
    [_txtFirstName release];
    [_txtLastName release];
    [_txtAddress release];
    [_txtCity release];
    [_btnCountry release];
    [_btnCheckbox release];
    [_btnSubmit release];
    
    SAFE_RELEASE_OBJECT(mHud);
    SAFE_RELEASE_OBJECT(dropdown_Countries);
    [_lbCountry release];
    [super dealloc];
}
- (void)setupUI{
    
    //Set hud
    mLoading = YES;
    [self initHUD:@"Loading...."];
    [mHud showWhileExecuting:@selector(waitting) onTarget:self withObject:nil animated:NO];
    
    //Set flag
    _isCheckbox = NO;
    _isClick = NO;
    _finishCountries = NO;
    
    //Set Notification keyboard
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    //Set scrollView
    _scrollParentView.contentSize = CGSizeMake(320, 530);
    _scrollParentView.frame = CGRectMake(0, 31, 320, [Utilities isDeviceFourInches] ? 385 :320);
    _scrollParentView.delegate = self;
    _isCheckbox = NO;
    _scrollParentView.backgroundColor = [UIColor clearColor];
    
    //Set textfields
    _txtEmail.delegate = self;
    
    _txtPass.delegate = self;
    _txtPass.secureTextEntry = YES;
    
    _txtConfirmPass.delegate = self;
    _txtConfirmPass.secureTextEntry = YES;
    
    _txtFirstName.delegate = self;
    _txtLastName.delegate = self;
    _txtAddress.delegate = self;
    _txtCity.delegate = self;
    
    
    //Set dropdownboxView
    dropdown_Countries = [[DropdownboxView alloc] initWithFrame:CGRectMake( _btnCountry.frame.origin.x, _btnCountry.frame.origin.y + _btnCountry.bounds.size.height + 1, 300, 0)];
    dropdown_Countries.typeAPI = countries_API;
    
    [dropdown_Countries getDataFromServer];
    dropdown_Countries.dropdownboxViewDelegate = self;
    dropdown_Countries.exclusiveTouch = YES;
    [_scrollParentView addSubview:dropdown_Countries];
    
}
- (void)enableTextfiels:(BOOL)enable{
    _txtEmail.userInteractionEnabled = enable;
    _txtPass.userInteractionEnabled = enable;
    _txtConfirmPass.userInteractionEnabled = enable;
    _txtFirstName.userInteractionEnabled = enable;
    _txtLastName.userInteractionEnabled = enable;
    _txtAddress.userInteractionEnabled = enable;
    _txtCity.userInteractionEnabled = enable;
}
- (void)resetTextField{
    _isCheckbox = NO;
    _txtEmail.text = @"";
    _txtPass.text = @"";
    _txtConfirmPass.text = @"";
    _txtFirstName.text = @"";
    _txtLastName.text = @"";
    _txtAddress.text = @"";
    _txtCity.text = @"";
    _lbCountry.text = @"";
    [_btnCheckbox setImage:[UIImage imageNamed:@"checkbox.png"] forState:UIControlStateNormal];
}

////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)submitRegisterAccount{
        dispatch_async(kBgQueue, ^{
            mLoading = YES;
            [self initHUD:@"Submitting...."];
            [mHud showWhileExecuting:@selector(waitting) onTarget:self withObject:nil animated:NO];
            
            
            NSString *urlString = [NSString stringWithFormat:@"%@%@%@", URL_island_API, signup_API, TOKEN__island];
            NSURL *url = [NSURL URLWithString:urlString];
            
            __block ASIFormDataRequest *requestServer = [ASIFormDataRequest requestWithURL:url];
            [requestServer setTimeOutSeconds:20];
            [requestServer addPostValue:[Utilities trimString:_txtEmail.text] forKey:@"email"];
            [requestServer addPostValue:[Utilities trimString:_txtPass.text] forKey:@"pwd1"];
            [requestServer addPostValue:[Utilities trimString:_txtConfirmPass.text] forKey:@"pwd2"];
            [requestServer addPostValue:[Utilities trimString:_txtFirstName.text] forKey:@"firstname"];
            [requestServer addPostValue:[Utilities trimString:_txtLastName.text] forKey:@"lastname"];
            [requestServer addPostValue:[Utilities trimString:_txtAddress.text] forKey:@"address"];
            [requestServer addPostValue:@"" forKey:@"address2"];
            [requestServer addPostValue:[Utilities trimString:_txtCity.text] forKey:@"city"];
            [requestServer addPostValue:[Utilities trimString:_lbCountry.text] forKey:@"country"];
            [requestServer addPostValue:_isCheckbox ? @"waiting" : @"customer" forKey:@"client"];
            [requestServer addPostValue:[[UIDevice currentDevice] systemVersion] forKey:@"os_version"];
            [requestServer addPostValue:@"IOS" forKey:@"os_name"];
            [requestServer addPostValue:[[UIDevice currentDevice] name] forKey:@"device_name"];
            
            ///////////////////////////////////////////////////////
            [requestServer setCompletionBlock:^{
                mLoading = NO;
                NSError *error = nil;
                NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:[requestServer responseData] options:kNilOptions error:&error];
                
                //Check eror server
                if (error) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[error description] delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
                    [alert show];
                    SAFE_RELEASE_OBJECT(alert);
                    return;
                }
                
                //Check error data
                NSDictionary *jsonError = [jsonData objectForKey:@"error"];
                if ([[jsonError objectForKey:@"code"] intValue] != 200) {
                    NSArray *messageArray = [jsonError objectForKey:@"message"];
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[messageArray objectAtIndex:0] delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
                    [alert show];
                    SAFE_RELEASE_OBJECT(alert);
                    return;
                }
                
                //Check data object
                NSDictionary *dataDic = [jsonData objectForKey:@"data"];
                
                ///Luu access_token xuong NSUserDefault
                NSString *accessToken = [dataDic objectForKey:@"access_token"];
                NSUserDefaults *access_tokenUserDefault = [NSUserDefaults standardUserDefaults];
                [access_tokenUserDefault setObject:accessToken forKey:access_token_eTicket_userDefault];
                [access_tokenUserDefault synchronize];
                
                
                
                NSDictionary *userDic = [dataDic objectForKey:@"user"];
                NSString *emailString = [userDic objectForKey:@"email"];
                [self resetTextField];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"Register Successfully with %@!!!", emailString] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
            }];
            
            ///////////////////////////////////////////////////////
            [requestServer setFailedBlock:^{
                mLoading = NO;
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Submit faild !!!" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
            }];
            
            [requestServer startSynchronous];
 
        });
}
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - btnRegister_Clicked
- (IBAction)btnRegister_Clicked:(id)sender{
    if (![self checkValidate]) {
        return;
    }
    
    [self submitRegisterAccount];
}

#pragma mark - btnCheckbox_Clicked
- (IBAction)btnCheckbox_Clicked:(id)sender{
    [_btnCheckbox setImage:[UIImage imageNamed:!_isCheckbox ? @"checkbox_checked.png" : @"checkbox.png"] forState:UIControlStateNormal];
    _isCheckbox = !_isCheckbox;
}

#pragma  mark - btnDropdown_Clicked
- (IBAction)btnDropdown_Clicked:(id)sender{
    if (!_finishCountries) {
        NSLog(@"Chua load xong data country");
        return;
    }
    
    [self textFieldResignFirstResponder];
    UIButton *button = (UIButton *)sender;
    if (button == _btnCountry) {
        _scrollParentView.scrollEnabled = NO;
        [self enableTextfiels:NO];
        ////////////////////////////////////////////////////
        [UIView animateWithDuration:0.2 animations:^{
            
            CGRect frame_dropdown_Countries = dropdown_Countries.frame;
            frame_dropdown_Countries.size.height = !_isClick ? 210 : 0;
            dropdown_Countries.frame = frame_dropdown_Countries;
            
            UITableView *tableCountries = (UITableView *)[dropdown_Countries.subviews objectAtIndex:0];
            CGRect frame_tableCountries = tableCountries.frame;
            frame_tableCountries.size.height = frame_dropdown_Countries.size.height;
            tableCountries.frame = frame_tableCountries;
            
        } completion:^(BOOL finished) {
            _isClick = !_isClick;
            if (!_isClick) {
                [self enableTextfiels:YES];
                _scrollParentView.scrollEnabled = YES;
                [_scrollParentView setContentOffset:CGPointMake(0, [Utilities isDeviceFourInches] ? (_scrollParentView.contentOffset.y -140) : (_scrollParentView.contentOffset.y - 160)) animated:YES];
            }
            else{
                [_scrollParentView setContentOffset:CGPointMake(0, [Utilities isDeviceFourInches] ? (_scrollParentView.contentOffset.y +140) : (_scrollParentView.contentOffset.y + 160)) animated:YES];
            }
        }];
    }

    
}

////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - checkValidate
- (BOOL)checkValidate{
    
    //Check Email
    if ([Utilities isEmptyString:[Utilities trimString:_txtEmail.text]] || ![Utilities isValidEmail:[Utilities trimString:_txtEmail.text]]) {
        remClickText = _txtEmail;
        [self alertTextField:@"Email is invalid !!!"];
        return  NO;
    }
    
    
    //Check Password
    NSString *password = [Utilities trimString:_txtPass.text];
    if ([Utilities isEmptyString:password] || [password length] < 6) {
        remClickText = _txtPass;
        [self alertTextField:@"Password is not empty & must be greater than 6 characters !!!"];
        return NO;
    }
    if ([Utilities haveEmoji:password]) {
        remClickText = _txtPass;
        [self alertTextField:@"Password must be not emoji !!"];
        return NO;
    }
    
    //Check Confirm Password
    NSString *confirmPassword = [Utilities trimString:_txtConfirmPass.text];
    if ([Utilities isEmptyString:confirmPassword] || [confirmPassword length] < 6 || ![confirmPassword isEqualToString:password]) {
        remClickText = _txtConfirmPass;
        [self alertTextField:@"Confirm password is not the same password !!!"];
        return NO;
    }
    if ([Utilities haveEmoji:confirmPassword]) {
        remClickText = _txtConfirmPass;
        [self alertTextField:@"Confirm password must be not emoji !!"];
        return NO;
    }
    
    //Check First name
    NSString *firstName = [Utilities trimString:_txtFirstName.text];
    if ([Utilities isEmptyString:firstName]) {
        remClickText = _txtFirstName;
        [self alertTextField:@"First name is not empty !!!"];
        return NO;
    }
    
    //Check Last name
    NSString *lastName = [Utilities trimString:_txtLastName.text];
    if ([Utilities isEmptyString:lastName]) {
        remClickText = _txtLastName;
        [self alertTextField:@"Last name is not empty !!!"];
        return NO;
    }
    
    //Check Address
    NSString *address = [Utilities trimString:_txtAddress.text];
    if ([Utilities isEmptyString:address]) {
        remClickText = _txtAddress;
        [self alertTextField:@"Address is not empty !!!"];
        return NO;
    }
    
    
    //Check City
    NSString *city = [Utilities trimString:_txtCity.text];
    if ([Utilities isEmptyString:city]) {
        remClickText = _txtCity;
        [self alertTextField:@"City is not empty !!!"];
        return NO;
    }
    
    
    return YES;
}


#pragma mark - Become & Resign textfield
- (void)textFieldResignFirstResponder{
    if (remClickText && [remClickText isFirstResponder]) {
        [remClickText resignFirstResponder];
    }
}
- (void)textFieldbecomeFirstResponder{
    if ([remClickText canBecomeFirstResponder]) {
        [remClickText becomeFirstResponder];
    }
}
- (void)alertTextField:(NSString *)message{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    alert.tag = ALERT_MESSAGE;
    [alert show];
    SAFE_RELEASE_OBJECT(alert);
}


#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == ALERT_MESSAGE) {
        [self textFieldbecomeFirstResponder];
    }
}
//////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - touchEvent
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
     NSLog(@"touchesBegan");
    [self textFieldResignFirstResponder];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
     NSLog(@"touchesMoved");
    [self textFieldResignFirstResponder];
}

//////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Textfield Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    remClickText = textField;
    tmpText = remClickText.text;
    NSLog(@"textFieldShouldBeginEditing");
    
    
    //Set contentOffset for scrollView when show keyboard
    firstContenOffset = _scrollParentView.contentOffset.y;
    float lastY = remClickText.frame.origin.y;
    [_scrollParentView setContentOffset:CGPointMake(0, lastY - 21) animated:YES];
    
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
     [_scrollParentView setContentOffset:CGPointMake(0, firstContenOffset) animated:YES];
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
     NSLog(@"textFieldDidEndEditing");
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"scrollViewWillBeginDecelerating");
    [self textFieldResignFirstResponder];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
     [self textFieldResignFirstResponder];
}


#pragma mark - Keyboard Notification
- (void)keyboardWillShow:(NSNotification *)notification{
    //Set contentOffset for scrollView when show keyboard
//    firstContenOffset = _scrollParentView.contentOffset.y;
//    float lastY = remClickText.frame.origin.y;
//    [_scrollParentView setContentOffset:CGPointMake(0, lastY - 21 - 9) animated:YES];
}
- (void)keyboardWillHide:(NSNotification *)notification{
    //Set contentOffset for scrollView when hide keyboard
     [_scrollParentView setContentOffset:CGPointMake(0, firstContenOffset) animated:YES];
}



#pragma mark - DropdownboxViewDelegate
- (void)DropdownboxView:(DropdownboxView *)dropdownboxView didSelectedCountry:(Country *)country{
    [UIView animateWithDuration:0.2 animations:^{
        
    
        CGRect frame_dropdown_Countries = dropdown_Countries.frame;
        frame_dropdown_Countries.size.height = 0;
        dropdown_Countries.frame = frame_dropdown_Countries;
        
        UITableView *tableCountries = (UITableView *)[dropdown_Countries.subviews objectAtIndex:0];
        CGRect frame_tableCountries = tableCountries.frame;
        frame_tableCountries.size.height = frame_dropdown_Countries.size.height;
        tableCountries.frame = frame_tableCountries;
        
        
    } completion:^(BOOL finished) {
        _isClick = !_isClick;
        _lbCountry.text = country.title;
        if (!_isClick) {
            [self enableTextfiels:YES];
            _scrollParentView.scrollEnabled = YES;
            [_scrollParentView setContentOffset:CGPointMake(0, _scrollParentView.contentOffset.y - 160) animated:YES];
        }
        else{
            [_scrollParentView setContentOffset:CGPointMake(0, _scrollParentView.contentOffset.y + 160) animated:YES];
        }
    }];
}
- (void)DropdownboxView:(DropdownboxView *)dropdownboxView didFinishDownload:(NSInteger)numberData withTypeDropboxIs:(NSString *)typeDropbox{
    mLoading = NO;
    if ([typeDropbox isEqualToString:countries_API]) {
        _finishCountries = YES;
        NSLog(@"da load xong contries vao combobox");
    }
}
- (void)DropdownboxViewLoadingDataFail:(DropdownboxView *)dropdownboxView{
    mLoading = NO;
}
- (void)DropdownboxViewRefeshData:(DropdownboxView *)dropdownboxView{
    mLoading = YES;
    [self initHUD:@"Loading...."];
    [mHud showWhileExecuting:@selector(waitting) onTarget:self withObject:nil animated:NO];
}
- (void)DropdownboxViewCancelRefeshData:(DropdownboxView *)dropdownboxView{
    if ([_registerViewDelegate respondsToSelector:@selector(registerViewDidSeclectCancelRefesh:)]) {
        [_registerViewDelegate registerViewDidSeclectCancelRefesh:self];
    }
}

#pragma mark - MBProgressHUD
-(void)initHUD:(NSString *)alert {
    if (mHud) {
        [mHud removeFromSuperview];
        SAFE_RELEASE_OBJECT(mHud);
    }
    mHud = [[MBProgressHUD alloc] initWithView:self];
    //    mHud.delegate = self;
    mHud.labelText = alert;
    mHud.dimBackground = YES;
    [self addSubview:mHud];
    
}
-(void)waitting{
    while (mLoading) {
        usleep(5000);
        if (_countTimeout >= 187*20 /* 187 ~ 3s ==>> 187 *20 ~ 1' */) {
            mLoading = NO;
            
        }
    }
}
@end
